/**
 * @brief TH06 华普微电子 温湿度传感器驱动
 * @author 张勇 / 2020-05-13
 */

#include "share/unios.h"
#include "th06.h"

std_err_t unidrv_simi2c_th06_read_temperature(unidrv_simi2c_t *dev, uint8_t addr, int *value) {
	// TH06 读写地址
	uint8_t	TH06_WRITE_ADDRESS = ((addr << 1) | 0);
	uint8_t	TH06_READ_ADDRESS  = ((addr << 1) | 1);

	#define TH06_MEASURE_RH_HM		0xE5 // Measure Relative Humidity, Hold Master Mode
	#define TH06_MEASURE_RH_NoHM	0xF5 // Measure Relative Humidity, No Hold Master Mode
	#define TH06_MEASURE_TEMP_HM	0xE3 // Measure Temperature, Hold Master Mode
	#define TH06_MEASURE_TEMP_NoHM	0xF3 // Measure Temperature, No Hold Master Mode
	#define TH06_READ_TEMP			0xE0 // Read Temperature Value from Previous RH Measurement
	#define TH06_RESET				0xFE // Reset
	#define TH06_WRITE_RHT_UREG1	0xE6 // Write RH/T User Register 1
	#define TH06_READ_RHT_UREG1		0xE7 // Read RH/T User Register 1
	
    uint16_t val;
	long temp;

	// 发送开始测量湿度的指令(保持 Master 模式)
	unidrv_simi2c_start(dev);
	if(!unidrv_simi2c_tx(dev, TH06_WRITE_ADDRESS))	 { unidrv_simi2c_stop(dev); return STD_ERR_TIMEOUT; }
	if(!unidrv_simi2c_tx(dev, TH06_MEASURE_TEMP_HM)) { unidrv_simi2c_stop(dev); return STD_ERR_TIMEOUT; }
	unidrv_simi2c_stop(dev);

	// 等待测量完毕
	unios_ms_delay(20);

	// 发送读取湿度指令，并读取湿度值
	unidrv_simi2c_start(dev);
	if(!unidrv_simi2c_tx(dev, TH06_READ_ADDRESS)) { unidrv_simi2c_stop(dev); return STD_ERR_TIMEOUT; }
	val = unidrv_simi2c_rx(dev, true);
	val <<= 8;
	val |= unidrv_simi2c_rx(dev, false);
	unidrv_simi2c_stop(dev);
	
	temp = val;
	temp *= 21965;
	temp >>= 13;
	temp /= 10;
	if(temp >= 4685) {
		temp -= 4685;
	} else {
		temp = 4685-temp;
		temp = ~temp+1;
	}

	*value = temp;
	return STD_ERR_OK;
}
